from django.shortcuts import render
from django.http import HttpResponse,Http404,JsonResponse

from .. models import Users
from web.settings import BASE_DIR
import time,random,os

from django.contrib.auth.decorators import permission_required


# Create your views here.
# 会员列表
@permission_required('myadmin.show_users',raise_exception=True)
def index(request):

    # 获取所有的会员数据
    obs = Users.objects.filter()

    # 获取搜索的类型
    types = request.GET.get('type',None)
    # 判断是否有搜索条件
    if types:
        # 获取搜索的关键字
        keywords = request.GET.get('keywords')
        # 判断搜索类型是否为sex
        if types == 'sex':
            sexlist = {'男':'1','女':'0'}
            obs = obs.filter(sex=sexlist[keywords])
        else:
            # 拼接条件参数
            data = {types+'__contains':keywords}
            # 执行条件搜索
            obs = obs.filter(**data) 

    # 数据分页
    # 获取当前页的页数
    pageindex = request.GET.get('p',1)
    # 导入分页类
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(obs, 2)

    # print(p.num_pages) 总页数 当前页
    # 获取分页页码 
    # num = p.page_range
    # 获取当前页的 数据
    userlist = p.page(pageindex)

     

    # 分配数据
    context = {'userlist':userlist}

    # 加载模板
    return render(request,'admin/user/index.html',context)


# 会员添加
@permission_required('myadmin.insert_users',raise_exception=True)
def add(request):
    # 加载 会员添加的表单
    return render(request,'admin/user/add.html')

# 执行添加
@permission_required('myadmin.insert_users',raise_exception=True)
def insert(request):

    # 获取上传的文件
    myfile = request.FILES.get('pic',None)

    # 先判断是否右文件上传
    if not myfile:
       pic = '/static/pics/users.jpeg'
    else:
        # 有文件上传
        pic = uploads(myfile)
        if not pic:
            return HttpResponse('<script>上传的文件类型错误,只能选择图片类型</script>')


    # 获取其他数据  request.POST
    data = request.POST.dict()
    del data['csrfmiddlewaretoken']
    data['pic'] = pic

    # 进行密码加密
    from django.contrib.auth.hashers import make_password, check_password
    data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')

    # 添加数据
    ob = Users.objects.create(**data)
    if ob:
        return HttpResponse('<script>alert("会员添加成功");location.href="/myadmin/user/index/"</script>')
    else:
        return HttpResponse('<script>alert("会员添加失败");history.back(-1)"</script>')



# 用户数据删除
@permission_required('myadmin.del_users',raise_exception=True)
def delete(request):
    if request.is_ajax():
        try:
            # 获取id,执行逻辑删除
            ob = Users.objects.get(id=request.GET['id'])
            ob.isDelete = True
            ob.save()
            return JsonResponse({'code':1,'msg':'删除成功'})
        except:
            return JsonResponse({'code':0,'msg':'删除失败'})
    else:
        # 返回一个404的错误页面
        raise Http404("Poll does not exist")



# 会员编辑
@permission_required('myadmin.edit_users',raise_exception=True)
def edit(request,uid):
    # 获取会员对象
    ob = Users.objects.get(id=uid)

    # 分配数据
    context = {'uinfo':ob}

    # 解析模板
    return render(request,'admin/user/edit.html',context)


# 执行修改
@permission_required('myadmin.edit_users',raise_exception=True)
def update(request):

    # 获取数据
    data = request.POST.dict()
    del data['csrfmiddlewaretoken']

    # 获取会员对象
    ob = Users.objects.get(id=data['id'])
    ob.username = data['username']
    ob.email = data['email']
    ob.age = data['age']
    ob.sex = data['sex']
    ob.phone = data['phone']


    # 判断是否更新了头像
    myfile = request.FILES.get('pic',None)
    if myfile:

        # 证明上传了新的头像,上传新头像,删除原来的头像
        # 判断是否为默认头像,如果不是,则删除
        if ob.pic != '/static/pics/users.jpeg':
            # 删除原来的头像
            try:
                os.remove(BASE_DIR+ob.pic)#/static/pics/a.jpg
            except:
                pass
        # 上传新的头像
        data['pic'] = uploads(myfile)

    # 执行更新
    ob.save()


    # 执行更新 必须使用查询集的结果调用,全部更新,更新全部字段,未指定的参数则为空
    # obs.update(**data) 

    # 执行更新,更新全部字段,未指定的参数则为空
    # ob.__dict__.update(**data)
    # ob.save()

    # update_or_create 更新全部字段,未指定的参数则为空
    # Users.objects.update_or_create(id=data['id'],defaults=data)


    return HttpResponse('<script>alert("更新成功");location.href="/myadmin/user/index/"</script>')


# 图片上传
def uploads(myfile):
    
   
    # 获取文件的后缀名
    h = myfile.name.split('.').pop()
    arr = ['jpg','png','gif','jpeg']
    # 判断上传的文件类型
    if h not in arr:
        return False

    # 重新定义新的文件名 时间搓+随机数
    filename = str(time.time())+str(random.random())+'.'+h

    # 执行文件上传
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")

    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()

    # 返回文件路径和文件名
    return '/static/pics/'+filename